package com.jinglin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinglin.entity.constants.Constants;
import com.jinglin.entity.po.CategoryInfo;
import com.jinglin.entity.po.VideoInfo;
import com.jinglin.entity.po.VideoInfoFilePost;
import com.jinglin.entity.po.VideoInfoPost;
import com.jinglin.exception.BusinessException;
import com.jinglin.mapper.CategoryInfoMapper;
import com.jinglin.redis.RedisUtils;

import com.jinglin.service.CategoryInfoService;
import com.jinglin.service.VideoInfoPostService;
import com.jinglin.service.VideoInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 分类信息 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2025-03-06
 */
@Service
public class CategoryInfoServiceImpl extends ServiceImpl<CategoryInfoMapper, CategoryInfo> implements CategoryInfoService {
    @Autowired
    private CategoryInfoMapper categoryInfoMapper;
    @Autowired
    private RedisUtils<List<CategoryInfo>> redisUtils;

    @Autowired
    @Lazy
    private VideoInfoService videoInfoService;
    @Autowired
    @Lazy
    private VideoInfoPostService videoInfoPostService;
    /*
     * 保存分类信息
     * */
    @Override
    public void saveCategory(CategoryInfo categoryInfo) {
        if (categoryInfo.getCategoryId() != null){
            //不为null，则是修改信息
            this.updateById(categoryInfo);
            this.saveCategoryToRedis();
            return;
        }
        Integer maxSort = categoryInfoMapper.getMaxSort(categoryInfo.getPCategoryId());
        if (maxSort == null) {
            maxSort = 1;
        }
        categoryInfo.setSort(maxSort + 1);

        this.save(categoryInfo);
        // 刷新一下缓存
        this.saveCategoryToRedis();
    }

    /*
     * 根据id删除分类
     * */
    @Override
    public void delCategory(String categoryId) {
        CategoryInfo categoryInfo = this.getById(categoryId);
        //查询分类下是否有视频，有视频的话不允许删除
        LambdaQueryWrapper<VideoInfoPost> videoPostWrapper = new LambdaQueryWrapper<>();
        videoPostWrapper.eq(VideoInfoPost::getCategoryId,categoryId);
        List<VideoInfoPost> videoInfoPostList = videoInfoPostService.list(videoPostWrapper);

        LambdaQueryWrapper<VideoInfo> videoWrapper = new LambdaQueryWrapper<>();
        videoWrapper.eq(VideoInfo::getCategoryId,categoryId);
        List<VideoInfo> videoInfoList = videoInfoService.list(videoWrapper);

        if (!videoInfoList.isEmpty() || !videoInfoPostList.isEmpty()){
            throw new BusinessException("分类下已有视频，不允许删除");
        }

        //查询分类下是否有子分类，有的话不让删
        LambdaQueryWrapper<CategoryInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryInfo::getPCategoryId,categoryInfo.getCategoryId());
        List<CategoryInfo> list = list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)){
            throw new BusinessException("删除失败，该分类下有其子分类，请将子分类删除");
        }

        this.removeById(categoryId);

        // 刷新一下缓存
        this.saveCategoryToRedis();
    }

    /*
    * 获取分类列表信息，并排序
    * */
    @Override
    public List<CategoryInfo> getCategoryList() {
        List<CategoryInfo> categoryInfos = (List<CategoryInfo>) redisUtils.get(Constants.REDIS_KEY_CATEGORY_LIST);
        if (categoryInfos != null){
            return categoryInfos;
        }
        List<CategoryInfo> list = this.list();
        // 升序
        list.sort((o1, o2) -> o1.getSort() - o2.getSort());

        // 刷新一下缓存
        this.saveCategoryToRedis();

        return this.getCategoryTree(list, "0");
    }

    /*
     * 修改排序
     * */
    @Override
    public void changeSort(String pCategoryId, String categoryIds) {
        String[] categoryArray = categoryIds.split(",");
        ArrayList<CategoryInfo> arrayList = new ArrayList<>();
        Integer sort = 0;
        for (String categoryId : categoryArray) {
            CategoryInfo categoryInfo = new CategoryInfo();
            categoryInfo.setCategoryId(categoryId);
            categoryInfo.setPCategoryId(pCategoryId);
            categoryInfo.setSort(++sort);
            arrayList.add(categoryInfo);
        }
        categoryInfoMapper.updateBatchSort(arrayList);
        // 刷新一下缓存
        this.saveCategoryToRedis();
    }

    private List<CategoryInfo> getCategoryTree(List<CategoryInfo> dataList,String pCategoryId){
        ArrayList<CategoryInfo> categoryInfos = new ArrayList<>();
        for (CategoryInfo categoryInfo : dataList) {
            if (categoryInfo.getPCategoryId().equals(pCategoryId)){
               categoryInfo.setChildren(getCategoryTree(dataList,categoryInfo.getCategoryId()));
               categoryInfos.add(categoryInfo);
            }
        }
        return categoryInfos;
    }

    /*
    * 直接刷新缓存。从数据库里面拿一次
    * */
    private void saveCategoryToRedis(){
        List<CategoryInfo> list = this.list();
        list.sort((o1, o2) -> o1.getSort() - o2.getSort());

        List<CategoryInfo> categoryTree = this.getCategoryTree(list, "0");
        redisUtils.set(Constants.REDIS_KEY_CATEGORY_LIST,categoryTree);
    }
}
